package com.java.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.dao.AdminMapper;
import com.java.model.Admin;
import com.java.model.Result;
import com.java.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Result login(Admin admin, HttpServletRequest request, Model model) {
        Admin use = adminMapper.login(admin);
        if (use!=null){
            request.getSession().setAttribute("user",use);
            model.addAttribute("admin",admin);
            return Result.success();
        }
        return Result.error("用户名或密码错误");
    }

    @Transactional
    @Override
    public Result save(Admin admin) {
        admin.setType("1");
        adminMapper.save(admin);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        for (int id : ids){
            adminMapper.remove(id);
        }
        return Result.success();
    }

    @Override
    public Result list(Admin admin) {
        PageHelper.startPage(admin.getPageNum(), admin.getPageSize());

        List<Admin> list = adminMapper.list(admin);
        PageInfo<Admin> pageInfo = new PageInfo(list);

        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result get(int id) {
        Admin admin = adminMapper.get(id);
        return Result.success(admin, null);
    }

    @Transactional
    @Override
    public Result modify(Admin admin) {
        adminMapper.modify(admin);
        return Result.success();
    }
}
